package com.zhx.websocket.signalr.config;

import com.microsoft.signalr.HubConnection;
import com.microsoft.signalr.HubConnectionBuilder;
import com.zhx.websocket.signalr.comm.CommContruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

/**
 * @author ：zhanghaixuan
 * @date ：Created in 2019-07-25 10:20
 * @description：用途:
 * @modified By：zhanghaixuan
 * @version: 1.0
 */
@Slf4j
@Configuration
public class SignalrClientConfig implements BeanPostProcessor {

    private String targetBeanName = "hubConnection";

    @Autowired
    private HubConnection hubConnection;

    @Autowired
    private DefaultListableBeanFactory defaultListableBeanFactory;

    @Bean
    public HubConnection hubConnection(){
        HubConnection hubConnection = HubConnectionBuilder.create(CommContruct.url)
                .build();

        hubConnection.start().blockingAwait();

        hubConnection.on(CommContruct.login_url,(message)->{
            log.info("远程连接APP login 成功");
        },String.class);

        hubConnection.on(CommContruct.event_url,(message)->{
            /**
             * 写入库逻辑
             */
            System.out.println("返回数据----->"+message);
        }, HashMap.class);

        hubConnection.send(CommContruct.login_url,  CommContruct.token);

        return hubConnection;
    }


    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        if (beanName.equals(targetBeanName) && !hubConnection.getConnectionState().equals("CONNECTED")) {
            boolean containsBean = defaultListableBeanFactory.containsBean(targetBeanName);
            if (containsBean) {
                //移除bean的定义和实例
                defaultListableBeanFactory.removeBeanDefinition(targetBeanName);
            }
            //注册新的bean定义和实例
            defaultListableBeanFactory.registerBeanDefinition(targetBeanName, BeanDefinitionBuilder.genericBeanDefinition(HubConnection.class).getBeanDefinition());
            return hubConnection();
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        return bean;
    }
}
